﻿<%@ WebHandler Language="C#" Class="UpdateCustomerRelation" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using LdExpress;

public class UpdateCustomerRelation : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        if (!string.IsNullOrEmpty(context.Request.Params["offerprice"]) && context.Request.Params["offerprice"].ToLower() == "offerprice")
        {
            int numofpage = 0;
            List<dynamic> source = new List<dynamic>();
            string condition = " AND CostStatus=1 ";
            condition += " AND CustRelId=" + context.Request.Params["ID"].ToString();
            int page_number = int.Parse(context.Request.Params["page_number"]);
            int itemPerPage = 5;
            string show_type = context.Request.Params["showtype"];
            if (show_type.ToLower() == "all")
            {
                itemPerPage = -1;
                page_number = -1;
            }
            BuildListCustomerOfferPrices(context, condition, itemPerPage, page_number, out numofpage, out source, GV.cn, GV.trans);
            if (source.Count > 0)
            {
                System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
                context.Response.Write(js.Serialize(source));
            }
            else
                context.Response.Write("Empty");
        }
        else
        {
            int nPermissions = 0;
            if (context.Request.Params["page"] == "customerstore")
            {
                if (context.Session["customerstore"] != null) nPermissions = int.Parse(context.Session["customerstore"].ToString());
            }
            else
            {
                if (context.Session["customerrelation"] != null) nPermissions = int.Parse(context.Session["customerrelation"].ToString());
            }


            if (context.Session["superadmin"] != null
                && int.Parse(context.Session["superadmin"].ToString()) >= 7)
                nPermissions = 10;

            if (nPermissions <= 0)
            {
                context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject("ACCESS DENIED"));
                return;
            }
            var vrs = context.Request.Params["version"];
            if (string.IsNullOrEmpty(vrs))
            {
                UpdateCustomerRelationV1(context);
            }
            else if (vrs == "2")
            {
                UpdateCustomerRelationV2(context);
            }
            else if (vrs.ToUpper() == "PO" || vrs.ToUpper() == "BLACKLIST")
            {
                MoveCustomerTosStores(context);
            }
        }
    }
    private void MoveCustomerTosStores(HttpContext context)
    {
        try
        {
            string items = context.Request.Params["items"];
            string custType = context.Request.Params["version"].ToString().ToLower();
            List<CustOnlyReport> udpitems = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CustOnlyReport>>(items);
            //IEnumerable<CustOnlyReport> result = from v in udpitems
            //                                     select v;
            foreach (CustOnlyReport cust in udpitems)
            {
                CustomerRelation obj = new CustomerRelation();
                long ID = long.Parse(cust.ID);
                obj.ID = ID;
                obj.Load(LdExpress.GV.cn, LdExpress.GV.trans);
                if (obj == null)
                    return;
                obj.UserID = -1;
                if (custType == "po")
                    obj.Archive = 0;
                else if (custType == "blacklist")
                    obj.Archive = 1;
                obj.Report = cust.Report;
                obj.LastUpdate = DateTime.Now;
                if (obj.Report.Length > 30)
                {
                    obj.Save(GV.cn, GV.trans);
                    //Update Duplicate
                    if (obj.Code.Length > 0)
                    {
                        string sql = "UPDATE tbl_customeractive set Duplicate=0 WHERE code='" + DBModule.RefineString(obj.Code) + "'";
                        DBModule.ExecuteNonQuery(sql, GV.cn, GV.trans);
                    }
                }
                else
                {
                    Output("Update Error!", context);
                }

            }
            Output("sucessful", context);
        }
        catch (Exception ex)
        {
            context.Response.Write(ex.Message + ex.StackTrace != null ? ex.StackTrace.ToString() : "");
            Output("Update Error!", context);
        }


    }
    private void UpdateCustomerRelationV1(HttpContext context)
    {
        try
        {
            string Goods = context.Request.Params["Goods"].Trim();
            string GoodsEx = context.Request.Params["GoodsEx"].Trim();
            string Name = context.Request.Params["Name"].Trim();
            string Code = context.Request.Params["Code"].Trim();
            string Address = context.Request.Params["Address"].Trim();
            string Tel = context.Request.Params["Tel"].Trim();
            string Mobile = context.Request.Params["Mobile"].Trim();
            string Email = context.Request.Params["Email"].Trim();
            string Social = context.Request.Params["Social"].Trim();
            string Pic = context.Request.Params["pic"].Trim();
            string Position = context.Request.Params["Position"].Trim();
            string Routers = context.Request.Params["Routers"].Trim();
            string Vols = context.Request.Params["Vols"].Trim();
            long ID = long.Parse(context.Request.Params["ID"].Trim());
            string Pol = context.Request.Params["Pol"].Trim();
            string Report = context.Request.Params["Report"].Trim();

            string _type = context.Request.Params["type"];

            LdExpress.CustomerRelation obj = new LdExpress.CustomerRelation();

            if (Name.Trim() == "")
            {
                context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject("NAME_BLANK"));
                return;
            }

            obj.ID = ID;
            obj.Load(LdExpress.GV.cn, LdExpress.GV.trans);
            if (obj == null)
                return;

            //obj.Name = Name;
            obj.Name = new System.Text.RegularExpressions.Regex(@"\s+").Replace(Name, " ");
            obj.Name = System.Text.RegularExpressions.Regex.Replace(obj.Name.ToLower(), "[A-Z]", delegate(System.Text.RegularExpressions.Match match)
            {
                string temp = match.ToString();
                return char.ToLower(temp[0]).ToString();
            });
            obj.Name = System.Text.RegularExpressions.Regex.Replace(obj.Name, "\\b[\\w]\\w*", delegate(System.Text.RegularExpressions.Match match)
            {
                string temp = match.ToString();
                return char.ToUpper(temp[0]).ToString() + temp.Substring(1);
            });
            obj.Code = Code;
            obj.Address = Address;
            obj.Tel = Tel;
            obj.Mobile = Mobile;
            obj.Email = Email;
            obj.Pic = Pic;
            obj.Position = Position;
            obj.Social = Social;
            obj.Routers = Routers;
            obj.Vols = Vols;
            if (obj.Archive != 2)
                obj.LastUpdate = DateTime.Now;
            obj.Pol = Pol;
            obj.Report = Report;
            Customers cus = new Customers();
            if (obj.PicID > 0)
            {
                //cus.ID = obj.PicID;
                //cus.Load(LdExpress.GV.cn, LdExpress.GV.trans);
                //cus.HoTen = obj.Pic;
                //cus.Save(LdExpress.GV.cn, LdExpress.GV.trans);
            }
            else if (obj.Pic != "")
            {
                cus.HoTen = obj.Pic;
                obj.PicID = cus.Save(LdExpress.GV.cn, LdExpress.GV.trans);
            }

            if (!string.IsNullOrEmpty(_type))
            {
                //if (LdExpress.CustomerRelation.IsCodeExisting(obj.Code, obj.ID, LdExpress.GV.cn, LdExpress.GV.trans))
                //{
                //    obj.Duplicate = 1;
                //}
                //else
                //    obj.Duplicate = 0;
            }
            else
            {
                obj.Goods = Goods;
                obj.GoodsEx = GoodsEx;
            }

            obj.Save(LdExpress.GV.cn, LdExpress.GV.trans);
            LdExpress.UserObjectsLog.SaveObjectActionLog(long.Parse(context.Session["logined_id"].ToString()), "customerrelation", "Edit", LdExpress.GV.cn, LdExpress.GV.trans);
            context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(DateTime.Now.ToString("dd-MM-yyyy")));
        }
        catch (Exception ex)
        {
            context.Response.Write(ex.Message + ex.StackTrace != null ? ex.StackTrace.ToString() : "");
        }
    }

    private void UpdateCustomerRelationV2(HttpContext context)
    {
        string items = context.Request.Params["items"];
        List<LdExpress.CustomerRelation> udpitems = Newtonsoft.Json.JsonConvert.DeserializeObject<List<LdExpress.CustomerRelation>>(items);
        string ids = "";
        ids = string.Join(",", udpitems.Select(q => q.ID));
        System.Data.DataSet ds = new System.Data.DataSet();
        string condition = "";
        if (!string.IsNullOrEmpty(ids))
        {
            condition = " and tbl_CustomerRelation.ID in (" + ids + ")";
        }
        else
        {
            context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject("not valid"));
        }
        int nNumOfPages = 0;
        int totalitem = 0;
        LdExpress.CustomerRelation.GetList(condition, "", 999, 1, out nNumOfPages, out totalitem, out ds, LdExpress.GV.cn, LdExpress.GV.trans);
        Array arr = udpitems.ToArray();

        if (ds.Tables.Count > 0)
        {
            foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
            {
                long ID = long.Parse(dr["ID"].ToString().Trim());

                CustomerRelation newcus = udpitems.First(q => q.ID == ID);
                CustomerRelation obj = new CustomerRelation();

                string Goods = dr["Goods"].ToString().Trim();
                string GoodsEx = dr["GoodsEx"].ToString().Trim();
                string HsGoods = dr["HsGoods"].ToString().Trim();
                string HsGoodsEx = dr["HsGoodsEx"].ToString().Trim();
                string Name = dr["Name"].ToString().Trim();
                string Code = dr["Code"].ToString().Trim();
                string Address = dr["Address"].ToString().Trim();
                string Tel = dr["Tel"].ToString().Trim();
                string Mobile = dr["Mobile"].ToString().Trim();
                string Email = dr["Email"].ToString().Trim();
                string Social = dr["Social"].ToString().Trim();
                string Pic = dr["pic"].ToString().Trim();
                string Position = dr["Position"].ToString().Trim();
                string Routers = dr["Routers"].ToString().Trim();
                string Vols = dr["Vols"].ToString().Trim();
                string Pol = dr["Pol"].ToString().Trim();
                string Report = dr["Report"].ToString().Trim();
                long _type = long.Parse(dr["ListType"].ToString());

                //items:[{'ID':'497','Name':'C.Ty Tnhh Nhựa Và Cao Su Kiến Phát Việt Nam','Address':'sds','Pic':'','Position':'','Tel':'','Mobile':'','Email':'','Social':'','Pol':'','Routers':'','Vols':'','Report':'','Goods':'','ListType':1,'UserID':1,'Description':'','Sort':0,'Owner':0,'Duplicate:0,'Level':0,'AutoLevel:0,'LastUpdate':'Thu Feb 21 2013'}]

                if (Name.Trim() == "")
                {
                    context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject("NAME_BLANK"));
                    return;
                }

                obj.ID = ID;
                obj.Load(LdExpress.GV.cn, LdExpress.GV.trans);
                if (obj == null)
                    return;

                obj.Name = new System.Text.RegularExpressions.Regex(@"\s+").Replace(Name, " ");
                obj.Name = System.Text.RegularExpressions.Regex.Replace(obj.Name.ToLower(), "[A-Z]", delegate(System.Text.RegularExpressions.Match match)
                {
                    string temp = match.ToString();
                    return char.ToLower(temp[0]).ToString();
                });
                obj.Name = System.Text.RegularExpressions.Regex.Replace(obj.Name, "\\b[\\w]\\w*", delegate(System.Text.RegularExpressions.Match match)
                {
                    string temp = match.ToString();
                    return char.ToUpper(temp[0]).ToString() + temp.Substring(1);
                });
                obj.Code = HttpUtility.HtmlDecode(newcus.Code);
                obj.Address = HttpUtility.HtmlDecode(newcus.Address);
                obj.Tel = HttpUtility.HtmlDecode(newcus.Tel);
                obj.Mobile = HttpUtility.HtmlDecode(newcus.Mobile);
                obj.Email = HttpUtility.HtmlDecode(newcus.Email);
                obj.Pic = HttpUtility.HtmlDecode(newcus.Pic);
                obj.Position = HttpUtility.HtmlDecode(newcus.Position);
                obj.Social = HttpUtility.HtmlDecode(newcus.Social);
                obj.Routers = HttpUtility.HtmlDecode(newcus.Routers);
                obj.Vols = HttpUtility.HtmlDecode(newcus.Vols);
                if (obj.Archive != 2)
                    obj.LastUpdate = DateTime.Now;
                obj.Pol = HttpUtility.HtmlDecode(newcus.Pol);
                obj.Report = HttpUtility.HtmlDecode(newcus.Report);
                obj.Goods = HttpUtility.HtmlDecode(newcus.Goods);
                obj.GoodsEx = HttpUtility.HtmlDecode(newcus.GoodsEx);
                obj.HsGoods = HttpUtility.HtmlDecode(newcus.HsGoods);
                obj.HsGoodsEx = HttpUtility.HtmlDecode(newcus.HsGoodsEx);
                obj.Name = HttpUtility.HtmlDecode(newcus.Name);

                //khong update inline
                obj.ListType = long.Parse(dr["ListType"].ToString());
                obj.UserID = long.Parse(dr["UserID"].ToString());
                //obj.GoodsEx = dr["GoodsEx"].ToString();
                //obj.Goods = dr["Goods"].ToString();
                obj.Description = dr["Description"].ToString();
                obj.Sort = int.Parse(dr["Sort"].ToString());
                obj.Owner = long.Parse(dr["Owner"].ToString());
                obj.Duplicate = long.Parse(dr["Duplicate"].ToString());
                obj.Level = long.Parse(dr["Level"].ToString());
                obj.AutoLevel = long.Parse(dr["AutoLevel"].ToString());
                obj.CusLevel_Limit = dr["CusLevel_Limit"].ToString();
                obj.CusLevel_Liabilities = dr["CusLevel_Liabilities"].ToString();
                obj.CusLevel_Note = dr["CusLevel_Note"].ToString();
                obj.CusLevel_TB = dr["CusLevel_TB"].ToString();
                obj.CusLevel_Debts_Incurred = dr["CusLevel_Debts_Incurred"].ToString();
                obj.ListType = _type;
                Customers cus = new Customers();
                if (obj.PicID > 0)
                {
                    //cus.ID = obj.PicID;
                    //cus.Load(LdExpress.GV.cn, LdExpress.GV.trans);
                    //cus.HoTen = obj.Pic;
                    //cus.Save(LdExpress.GV.cn, LdExpress.GV.trans);
                }
                else if (obj.Pic != "")
                {
                    cus.HoTen = obj.Pic;
                    obj.PicID = cus.Save(LdExpress.GV.cn, LdExpress.GV.trans);
                }
                obj.Save(LdExpress.GV.cn, LdExpress.GV.trans);
            }
            LdExpress.UserObjectsLog.SaveObjectActionLog(long.Parse(context.Session["logined_id"].ToString()), "customerrelation", "Edit", LdExpress.GV.cn, LdExpress.GV.trans);
        }

        context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(items));
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }


    private void BuildListCustomerOfferPrices(HttpContext context, string Codition, int NumOfItemsPerPage, int PageNo, out int nNumOfPages, out List<dynamic> source, MySql.Data.MySqlClient.MySqlConnection cn, MySql.Data.MySqlClient.MySqlTransaction trans)
    {
        System.Data.DataSet ds = null;
        source = new List<dynamic>();
        //source.Add(new { strID = "", Pol = "tttt", Pod = "", Vols = "", Dc20 = "", Dc40 = "", Hc40 = "", Rf20 = "", Rf40 = "", CBM = "", KG = "", Dc20_Sell = "", Dc40_Sell = "", Hc40_Sell = "", Rf20_Sell = "", Rf40_Sell = "", CBM_Sell = "", KG_Sell = "", Agent = "", OfferPrice_Note = "", LastUpdate = "", strAction = "", CostStatus = "" });
        //Get List by SoIDs
        nNumOfPages = 0;
        int line = 1;
        try
        {
            int nPermissions = 0;
            if (context.Session["logined_id"] != null)
            {
                if (context.Session["customerrelation"] != "") nPermissions = int.Parse(context.Session["customerrelation"].ToString());
            }


            string strCondition = Codition;
            strCondition += " And CustRelId=" + context.Request.Params["ID"].ToString();
            CustomerOfferPrices obj = new CustomerOfferPrices();
            line = 2;
            obj.GetList(strCondition, "", "lastupdate desc", NumOfItemsPerPage, PageNo, out nNumOfPages, out ds, GV.cn, GV.trans);

            string strAllQueryString = "";

            foreach (string strKey in context.Request.QueryString.AllKeys)
            {
                if (strKey != null)
                {
                    if ((strKey.ToLower() != "action") && (strKey.ToLower() != "id"))
                        strAllQueryString = strAllQueryString + "&" + strKey + "=" + context.Request.Params[strKey].ToString();
                }
            }
            line = 3;
            if (strAllQueryString.Length >= 1)
                strAllQueryString = strAllQueryString.Substring(1);

            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                int count = 0;
                int NumOfItems1 = 0;
                foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
                {
                    count++;
                    NumOfItems1 = count;
                    string strCustID = dr["CustRelID"].ToString();
                    string strTemp = "";
                    strTemp = strCustID;
                    strTemp = strTemp.Replace("'", "\\'");
                    string strID = dr["Id"].ToString();
                    string strCostNumber = dr["CostNumber"].ToString();
                    string strIndex = count.ToString();
                    string strStatus = "1";
                    if (int.Parse(dr["CostStatus"].ToString()) > 0)
                        strStatus = "0";
                    string Vols = "<a href=\"javascript:doOpenQuantity('" + System.Web.HttpUtility.HtmlEncode(dr["ID"].ToString()) + "','" + System.Web.HttpUtility.HtmlEncode(strTemp) + "','" + strStatus + "')\">Edit</a>";
                    //dr["Vols"].ToString();
                    //string Routers = dr["Routers"].ToString();
                    string Pol = dr["Pol"].ToString();
                    string Pod = dr["Pod"].ToString();
                    string Dc20 = dr["Dc20"].ToString();
                    string Dc40 = dr["Dc40"].ToString();
                    string Hc40 = dr["Hc40"].ToString();
                    string Rf20 = dr["Rf20"].ToString();
                    string Rf40 = dr["Rf40"].ToString();
                    string CBM = dr["CBM"].ToString();
                    string KG = dr["KG"].ToString();
                    string Dc20_Sell = dr["Dc20_Sell"].ToString();
                    string Dc40_Sell = dr["Dc40_Sell"].ToString();
                    string Hc40_Sell = dr["Hc40_Sell"].ToString();
                    string Rf20_Sell = dr["Rf20_Sell"].ToString();
                    string Rf40_Sell = dr["Rf40_Sell"].ToString();
                    string CBM_Sell = dr["CBM_Sell"].ToString();
                    string KG_Sell = dr["KG_Sell"].ToString();
                    string Agent = dr["Agent"].ToString();
                    string PricingName = dr["PricingName"].ToString();
                    string OfferPrice_Note = dr["OfferPrice_Note"].ToString();
                    string LastUpdate = "";
                    if (dr["LastUpdate"].ToString() != "")
                        //LastUpdate = DateTime.Parse(dr["LastUpdate"].ToString()).ToString("ddMMyy");
                        LastUpdate = "<font color=\"#0000ff\">" + DateTime.Parse(dr["LastUpdate"].ToString()).ToString("ddMMyy") + "</font>";
                    string strAction = "";
                    if (nPermissions > 7)
                    {
                        strAction += " <a href=\"javascript:doDelete('" + System.Web.HttpUtility.HtmlEncode(dr["ID"].ToString()) + "','" + System.Web.HttpUtility.HtmlEncode(strTemp) + "','DeleteOfferPrice')\">Delete</a>";
                    }
                    if (nPermissions >= 3)
                    {

                        strAction += " - <a href=\"javascript:doOpenCosted('" + System.Web.HttpUtility.HtmlEncode(dr["ID"].ToString()) + "','" + System.Web.HttpUtility.HtmlEncode(strTemp) + "')\">";
                        if (dr["CostNumber"].ToString().Trim().Length > 0)
                            strAction += "Costed</a>";
                        else
                            strAction += "Costing</a>";

                    }
                    string CostStatus = dr["CostStatus"].ToString();
                    dynamic item = new { strID = strID, strCostNumber = strCostNumber, Pol = Pol, Pod = Pod, Vols = Vols, Dc20 = Dc20, Dc40 = Dc40, Hc40 = Hc40, Rf20 = Rf20, Rf40 = Rf40, CBM = CBM, KG = KG, Dc20_Sell = Dc20_Sell, Dc40_Sell = Dc40_Sell, Hc40_Sell = Hc40_Sell, Rf20_Sell = Rf20_Sell, Rf40_Sell = Rf40_Sell, CBM_Sell = CBM_Sell, KG_Sell = KG_Sell, Agent = Agent, PricingName = PricingName, OfferPrice_Note = OfferPrice_Note, LastUpdate = LastUpdate, strAction = strAction, CostStatus = CostStatus };
                    source.Add(item);
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(line.ToString() + ex.Message);
        }
    }
    private void Output(string message, HttpContext context)
    {
        context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new { Message = message, Date = DateTime.Now.ToString("dd-MM-yyy") }));
    }
    public class CustOnlyReport
    {
        public string ID { get; set; }
        public string Report { get; set; }
    }
}
